package com.southwind.springboottest.controller;

import com.southwind.springboottest.entity.BorrowRecord;
import com.southwind.springboottest.entity.Book;
import com.southwind.springboottest.entity.User;
import com.southwind.springboottest.repository.BorrowRecordRepository;
import com.southwind.springboottest.repository.BookRepository;
import com.southwind.springboottest.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/borrow")
public class BorrowHandler {
    @Autowired
    private BorrowRecordRepository borrowRecordRepository;
    
    @Autowired
    private BookRepository bookRepository;

    @GetMapping("/findAll/{page}/{size}")
    public ResponseEntity<Map<String, Object>> findAll(
            @PathVariable("page") Integer page,
            @PathVariable("size") Integer size) {
        PageRequest request = PageRequest.of(page, size);
        Page<BorrowRecord> result = borrowRecordRepository.findAll(request);
        
        Map<String, Object> response = new HashMap<>();
        response.put("data", result.getContent());
        response.put("total", result.getTotalElements());
        response.put("page", page);
        response.put("size", size);
        
        return ResponseEntity.ok(response);
    }

    @Autowired
    private UserRepository userRepository;

    @PostMapping
    @Transactional
    public String createBorrow(@RequestBody Map<String, Object> request) {
        try {
            // Log request data
            System.out.println("Borrow request data: " + request.toString());
            
            // Validate request structure
            if (request.get("book") == null || request.get("user") == null) {
                throw new IllegalArgumentException("请求参数不完整");
            }
            
            // Get book ID and validate book status
            Map<String, Object> bookMap = (Map<String, Object>) request.get("book");
            Integer bookId = (Integer) bookMap.get("id");
            if (bookId == null) {
                throw new IllegalArgumentException("图书ID不能为空");
            }
            System.out.println("Book ID: " + bookId);
            
            Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new IllegalArgumentException("图书不存在"));
            
            System.out.println("Book found: " + book);
            
            if (book.getAbled() != 1) {
                throw new IllegalArgumentException("该图书不可借阅");
            }
            
            // Get user ID and validate user
            Integer userId = (Integer) ((Map<String, Object>) request.get("user")).get("id");
            System.out.println("User ID: " + userId);
            
            if (userId == null) {
                throw new IllegalArgumentException("用户ID不能为空");
            }
            
            User user = userRepository.findById(userId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
            
            System.out.println("User found: " + user);
            
            // Create and save borrow record
            BorrowRecord borrowRecord = new BorrowRecord();
            // Set borrow time from request or use current time
            Date borrowTime = new Date();
            if (request.get("borrowTime") != null) {
                try {
                    borrowTime = new Date((String)request.get("borrowTime"));
                } catch (Exception e) {
                    System.err.println("Invalid borrow time format, using current time");
                }
            }
            borrowRecord.setBorrowTime(borrowTime);
            borrowRecord.setBook(book);
            borrowRecord.setUser(user);
            borrowRecord.setApproved(false);

            // Save in transaction
            try {
                System.out.println("Attempting to save borrow record...");
                System.out.println("Book ID: " + borrowRecord.getBook().getId());
                System.out.println("User ID: " + borrowRecord.getUser().getUserid());
                
                borrowRecord = borrowRecordRepository.saveAndFlush(borrowRecord);
                System.out.println("Saved borrow record ID: " + borrowRecord.getBorrowRecordId());
                
                // Verify the saved record
                BorrowRecord savedRecord = borrowRecordRepository.findById(borrowRecord.getBorrowRecordId()).orElse(null);
                System.out.println("Verified saved record: " + savedRecord);
                
                return "success";
            } catch (Exception e) {
                System.err.println("Failed to save borrow record: " + e.getMessage());
                e.printStackTrace();
                
                // Log detailed SQL error if available
                if (e.getCause() != null) {
                    System.err.println("Root cause: " + e.getCause().getMessage());
                    if (e.getCause().getCause() != null) {
                        System.err.println("Nested exception: " + e.getCause().getCause().getMessage());
                    }
                }
                
                throw new RuntimeException("保存借阅记录失败: " + e.getMessage());
            }
        } catch (Exception e) {
            System.err.println("Error creating borrow record: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    @PutMapping("/approve/{borrowRecordId}")
    public String approveBorrow(@PathVariable("borrowRecordId") Integer borrowRecordId) {
        BorrowRecord record = borrowRecordRepository.findById(borrowRecordId).get();
        record.setApproved(true);
        borrowRecordRepository.save(record);
        
        // Update book status
        Book book = record.getBook();
        book.setAbled(0); // 0 means disabled
        bookRepository.save(book);
        
        return "success";
    }

    @PutMapping("/return/{borrowRecordId}")
    public String returnBook(@PathVariable("borrowRecordId") Integer borrowRecordId) {
        BorrowRecord record = borrowRecordRepository.findById(borrowRecordId).get();
        record.setReturnTime(new Date());
        borrowRecordRepository.save(record);
        
        // Update book status
        Book book = record.getBook();
        book.setAbled(1); // 1 means enabled
        bookRepository.save(book);
        
        return "success";
    }

    @DeleteMapping("/delete/{borrowRecordId}")
    @Transactional
    public String deleteBorrowRecord(@PathVariable("borrowRecordId") Integer borrowRecordId) {
        try {
            // Check if record exists
            BorrowRecord record = borrowRecordRepository.findById(borrowRecordId)
                .orElseThrow(() -> new IllegalArgumentException("借阅记录不存在"));
            
            // If book was borrowed but not returned, restore book status
            if (record.getApproved() && record.getReturnTime() == null) {
                Book book = record.getBook();
                book.setAbled(1); // Set book to available
                bookRepository.save(book);
            }
            
            // Delete the record
            borrowRecordRepository.deleteById(borrowRecordId);
            
            return "success";
        } catch (Exception e) {
            throw new RuntimeException("删除借阅记录失败: " + e.getMessage());
        }
    }
}
